package com.example.tangjiangxu.rotatepicbrowserdemo;

import android.graphics.Camera;
import android.graphics.Matrix;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * Created by tangjiangxu on 4/5/17.
 */

public class Rotate3dAnimation extends Animation{
    private static final String TAG = "Rotate3dAnimation";
    /** 旋转开始的角度 **/
    private final float mFromDegrees;
    /** 旋转结束的角度 **/
    private final float mToDegrees;
    /** 旋转的中心点 **/
    private final float mCenterX;
    private final float mConterY;
    private final float mDepthZ;
    private final boolean mReverse;
    private Camera mCamera;

    public Rotate3dAnimation(float mFromDegrees, float mToDegrees, float mCenterX, float mConterY, float mDepthZ, boolean mReverse) {
        this.mFromDegrees = mFromDegrees;
        this.mToDegrees = mToDegrees;
        this.mCenterX = mCenterX;
        this.mConterY = mConterY;
        this.mDepthZ = mDepthZ;
        this.mReverse = mReverse;
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
        mCamera = new Camera();
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        Log.e(TAG, "applyTransformation: interpolatedTime:"  + interpolatedTime);
        final float fromDegrees = mFromDegrees;
        //计算当前旋转的角度
        float defrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

        float centerX = mCenterX;
        float centerY = mConterY;
        final Camera camera = mCamera;

        final Matrix matrix = t.getMatrix();

        camera.save();
        //Z轴进行一定的偏移，使视图有远离视角的感觉
        if (mReverse) {
            camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
        } else {
            camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
        }
        //绕Y轴旋转，产生立体旋转效果
        camera.rotateY(defrees);
        camera.getMatrix(matrix);
        camera.restore();
        //通过matrix确定旋转的中心点位置
        matrix.preTranslate(-centerX, -centerY);
        matrix.postTranslate(centerX, centerY);

    }
}
